// pages/coaches/coaches.js
import request from '../../utils/request'

Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    searchValue: '',
    selectedCategory: 0,
    categories: [],
    coaches: [],
    loading: false
  },

  onLoad() {
    this.loadCategories();
    this.loadCoaches();
  },

  // 加载分类
  loadCategories() {
    wx.request({
      url: this.data.backendUrl + 'get_coach_categories.php',
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            categories: res.data.categories
          });
        }
      }
    });
  },

  // 加载教练列表
  loadCoaches() {
    this.setData({ loading: true });
    wx.request({
      url: this.data.backendUrl + 'get_coaches.php',
      data: {
        category_id: this.data.selectedCategory,
        keyword: this.data.searchValue
      },
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            coaches: res.data.coaches
          });
        }
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 搜索变化
  onSearchChange(e) {
    this.setData({
      searchValue: e.detail
    });
    this.loadCoaches();
  },

  // 执行搜索
  onSearch() {
    this.loadCoaches();
  },

  // 选择分类
  selectCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      selectedCategory: categoryId
    });
    this.loadCoaches();
  },

  // 跳转到详情页
  goToDetail(e) {
    const coachId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/coach-detail/coach-detail?id=${coachId}`,
    });
  }
})